from django.http import HttpResponseBadRequest, HttpRequest, HttpResponse, JsonResponse
from .models import Post, Content
import math
from user.views import authontoken
import simplejson
from utls import getlogger

log = getlogger('post')


@authontoken
def pub(request: HttpRequest):
    try:
        payload = simplejson.loads(request.body)
        title = payload['title']
        author = request.user_id
        post = Post()
        post.title = title
        post.author_id = author
        try:
            post.save()
            cont = Content()
            content = payload['content']
            cont.content = content
            cont.post_id = post.id
            try:
                cont.save()
                log.info("用户{}文章上传成功".format(post.author.name))
                return JsonResponse({"user_id": post.id})
            except Exception  as e:
                log.error(e)
                log.error("用户{}文章上传失败".format(post.author.name))
                return HttpResponseBadRequest(b'con insert into failed')
        except Exception as e:
            log.error(e)
            log.error('post  data  insert  failed')
            return HttpResponseBadRequest(b'post  data  insert  failed')

    except  Exception as e:
        log.error(e)
        log.error('request  param  not  auth')
        return HttpResponseBadRequest(b'request  param  not  auth')


def get(request: HttpRequest, id):
    try:
        query = Post.objects.filter(pk=id).get()
        if not query:
            log.error("文章{}获取失败".format(query.title))
            return HttpResponseBadRequest(b'article  not exist')
        log.info("文章{}获取成功".format(query.title))
        return JsonResponse({
            "post": {
                "post_title": query.title,
                "author_id": query.author.id,
                "post_conent": query.content.content,
                "post_user": query.author.email,
                'date': query.pubdata,
                'post_name': query.author.name,
            }
        })
    except Exception as  e:
        log.error(e)
        log.error('article 00 not exist')
        return HttpResponseBadRequest(b'article 00 not exist')


def validate(d: dict, name: str, type_func, default, validate_func):
    try:
        result = type_func(d.get(name, default))
        result = validate_func(result, default)
    except:
        result = default
    return result


def getall(request: HttpRequest):
    size = validate(request.GET, 'size', int, 10, lambda x, y: x if x > 0 and x < 10 else y)
    page = validate(request.GET, 'page', int, 1, lambda x, y: x if x > 0 else y)
    start = (page - 1) * size  # 起始数据列表值
    postsall = Post.objects.all()
    posts = postsall[::-1][start:page * size]
    # 总数据，当前页，总页数
    count = postsall.count()
    # 总页数
    pages = math.ceil(count / size)
    # 当前页
    page = page
    # 当前页数量
    log.info("文章列表获取成功 page:{}  size:{}".format(page, size))
    return JsonResponse({
        "posts": [
            {
                "post_id": post.id,
                "post_title": post.title,
                "post_name": post.author.name,
            } for post in posts
        ],
        "pattern": {
            "count": count,
            "pages": pages,
            "page": page,
            "size": size,
        }
    })
